<style rel="stylesheet/scss" lang="scss" >
    .pro-gzq-home-log-info{
        .el-dialog.is-fullscreen{
            background-color: #f0f2f5;
            .el-dialog__body{
                height: 100%;
                overflow: auto;
                width: 1250px;
                margin: 0 auto;
                padding: 20px;
                background: #ffffff;
                position: relative;
            }
            .el-dialog__header{
                display: none;
            }
            .el-dialog__close{
                position: absolute;
                right:20px;
                top:20px;
                font-size: 20px;
                cursor: pointer;
            }
            .el-dialog__close:hover{
                color: #2f6bcf;
            }
            .info-box{
                border: 0;
                position: relative;
                padding:10px 10px 60px;
                .info-header{
                    text-align: center;
                    .title{
                        font-size: 18px;
                        font-weight: bold;
                    }
                    .sub-title{
                        font-size: 14px;
                        line-height: 24px;
                        color: #666666;
                    }

                }
                .content{
                    padding:10px 20px;
                    overflow: auto;
                    .label-top,
                    .text-num{
                        line-height: 30px;
                        color: #999999;
                    }
                    .text-num{
                        text-align: right;
                    }
                    .el-textarea{
                        textarea{
                            min-height:80px !important;
                        }
                    }
                    .change-user{
                        margin-left:20px;
                        cursor: pointer;
                        color:#396ad1;
                    }
                    .content-read{
                        min-height: 100px;
                        padding: 10px;
                        border-radius: 4px;
                    }
                    .content-item{
                        margin-bottom:20px;
                        .comments{
                            .comments-item{
                                padding: 10px 10px 10px 50px;
                                position: relative;
                                line-height: 24px;
                                .title{
                                    color:grey;
                                }
                                .remove{
                                    font-size: 12px;
                                    color: #ddd;
                                    margin-left: 10px;
                                    cursor: pointer;
                                    &:hover{
                                        color: #396ad1;
                                    }
                                }
                                .photo{
                                    position: absolute;
                                    left: 5px;
                                    top: 14px;
                                    .je-user-photo{
                                        cursor: auto;
                                    }
                                }
                            }
                        }
                        .comment-edit{
                            .text-num{
                                float: right;
                            }
                            .button{
                                margin:5px;
                            }
                        }
                        .download_list {
                            .download_item {
                                float: left;
                                width: 70px;
                                margin-top: 5px;
                                cursor: pointer;
                                .name {
                                    margin-top: 10px;
                                }
                                &:not(:first-child) {
                                    margin-left: 20px;
                                }
                            }
                            &:after {
                                content: '';
                                display: table;
                                clear: both;
                            }
                        }
                        .read_list {
                            .read_items {
                                width: 70px;
                                float: left;
                                margin-top: 10px;
                                .photo {
                                    width: 32px;
                                    height: 32px;
                                    border-radius: 100%;
                                    margin: 0 auto;
                                }
                                .name {
                                    margin-top: 10px;
                                    text-align: center;
                                }
                            }
                            &:after {
                                content: '';
                                display: table;
                                clear: both;
                            }
                        }
                    }
                }

                .buttonbar{
                    width:100%;
                    text-align: center;
                    padding: 10px 15px;
                    position: absolute;
                    bottom:0;
                    left:0;
                }

                .button{
                    padding: 5px;
                    // width: 90px;
                    line-height: 28px;
                    text-align: center;
                    background: #f2f2f2;
                    color: #333333;
                    display: inline-block;
                    font-size: 14px;
                    border-radius: 4px;
                    cursor: pointer;
                    margin: 0 5px;
                    &.button-blue{
                        background: #396ad1;
                        color: #ffffff;
                    }
                }
            }
        }
    }
</style>
<template>
  <div class="pro-gzq-home-log-info">
    <el-dialog
      :visible.sync="visible"
      top="0"
      fullscreen
    >
      <el-card
        class="info-box"
        shadow="never"
      >
        <div
          slot="header"
          class="clearfix info-header"
        >
          <div class="title">
            <span v-if="lang == 'zh_CN'">
              {{ info.time }}的工作{{ info.text }}报
            </span>
            <span v-else>
              {{ getTimeEn(info) }}
              {{ data.REPORT_BGLX_CODE=='RZ'?'Daily work':data.REPORT_BGLX_CODE=='ZB'?'Work weekly':'Work monthly report' }}
            </span>
          </div>
          <div class="sub-title">
            <span v-if="lang == 'zh_CN'">
              {{ data.SY_CREATEUSERNAME }} 于 {{ data.SY_CREATETIME }} 发布
            </span>
            <span v-else>
              {{ data.SY_CREATEUSERNAME }} At {{ data.SY_CREATETIME }} released it
            </span>
            
          </div>
        </div>
        <div
          ref="content"
          v-loading="loading" class="content" :style="contentStyle"
        >
          <div class="content-item">
            <div class="label-top">
              <span v-if=" info.type == 'RZ' ">{{ $t('_log.todayswork') }}<span style="color: red;">*</span>：</span>
              <span v-else>{{ $t('_log.this') }}{{ getEn(info.text) }}{{ $t('_log.jobsummary') }}<span style="color: red;">*</span>：</span>
            </div>
            <div
              v-show="!readOnly && isCurrentUser"
              class="content-edit"
            >
              <el-input
                type="textarea"
                resize="none"
                ref="work"
                maxlength="1000"
                v-model="data.REPORT_GZZJ"
                autosize
              />
              <div class="text-num">
                {{ (data.REPORT_GZZJ || '').length }}/1000
              </div>
            </div>
            <div
              v-show="readOnly || isDPUser"
              class="content-read"
              v-html="formatContent(data.REPORT_GZZJ, getEn('暂无内容'))" />
          </div>
          <div class="content-item">
            <div class="label-top">
              <span>{{ $t('_log.weiwancheng') }}：</span>
            </div>
            <div
              v-show="!readOnly && isCurrentUser"
              class="content-edit"
            >
              <el-input
                type="textarea"
                resize="none"
                ref="plan"
                maxlength="1000"
                v-model="data.REPORT_DWC"
                autosize
              />
              <div class="text-num">
                {{ (data.REPORT_DWC || '').length }}/1000
              </div>
            </div>
            <div
              v-show="readOnly || isDPUser"
              class="content-read"
              v-html="formatContent(data.REPORT_DWC,getEn('暂无内容'))" />
          </div>
          <div class="content-item">
            <div class="label-top">
              <span v-if=" info.type == 'RZ' ">{{ $t('_log.mingrijihua') }}：</span>
              <span v-else>{{ $t('_log.next') }}{{ getEn(info.text) }}{{ $t('_log.gongzuojihua') }} :</span>
            </div>
            <div
              v-show="!readOnly && isCurrentUser"
              class="content-edit"
            >
              <el-input
                type="textarea"
                resize="none"
                ref="plan"
                maxlength="1000"
                v-model="data.REPORT_GZJH"
                autosize
              />
              <div class="text-num">
                {{ (data.REPORT_GZJH || '').length }}/1000
              </div>
            </div>
            <div
              v-show="readOnly || isDPUser"
              class="content-read"
              v-html="formatContent(data.REPORT_GZJH,getEn('暂无内容'))" />
          </div>
          <div class="content-item">
            <div class="label-top">
              {{ $t('_log.gonzuoxinde') }}：
            </div>
            <div
              v-show="!readOnly && isCurrentUser"
              class="content-edit"
            >
              <el-input
                type="textarea"
                resize="none"
                ref="summary"
                maxlength="1000"
                v-model="data.REPORT_GZXD"
                autosize
              />
              <div class="text-num">
                {{ (data.REPORT_GZXD || '').length }}/1000
              </div>
            </div>
            <div
              v-show="readOnly || isDPUser"
              class="content-read"
              v-html="formatContent(data.REPORT_GZXD,getEn('暂无内容'))" />
          </div>
          <div v-show="readOnly || isDPUser"  class="content-item">
            <div class="label-top">
              {{ $t('_log.xiangguanfujian') }}：
            </div>
            <div
              v-if="filelist.length > 0"
              class="download_list"
            >
              <div
                v-for="(item, index) in filelist"
                :key="index"
                class="download_item"
                @click="download(item)"
              >
                <downloadItem :data="item" />
              </div>
            </div>
            <div
              v-else
              class="content-read"
            >
              {{ $t('_log.zanwufujian') }}
            </div>
          </div>
          <div v-show="!readOnly && isCurrentUser" class="content-item">
            <uploadbox
              :list="filelist"
              @upload="getList"
              :max="6"
            />
          </div>
          <div class="content-item">
            <div class="label-top">
              {{ $t('_log.read1') }} {{ data.readList.length }}
            </div>
            <div
              v-if="data.readList.length > 0"
              class="read_list"
            >
              <div
                v-for="(item, index) in data.readList"
                :key="index"
                class="read_items"
              >
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="item.values.SY_CREATETIME" placement="top"
                >
                  <div
                    class="photo"
                    v-html="formatPhoto(item.values.SY_CREATEUSERID)" 
                  />
                </el-tooltip>
                <p class="name">
                  {{ item.values.SY_CREATEUSERNAME }}
                </p>
              </div>
            </div>
            <div
              v-else
              class="content-read"
            >
              {{ $t('_log.noreading') }}
            </div>
          </div>
          <div class="content-item">
            <div class="label-top">
              {{ $t('_log.dianpingxinxi') }}：
              <span 
                v-if="isCurrentUser && !readOnly"
                class="change-user"
                @click="selectUser"
              >({{ $t('_log.reuser') }}：{{ data.REPORT_DPR_NAME || getEn('暂无内容') }}) {{ $t('_log.genghuandianpingren') }}</span>
            </div>
            <div
              v-if="comments.length > 0"
              class="comments">
              <div
                v-for="(item,index) in comments"
                :key="item" class="comments-item"
              >
                <div class="title">
                  <!-- 姓名 -->
                  <span class="name" v-if="!item.REPORTDP_REPLY_DPID">{{ item.SY_CREATEUSERNAME }}</span>
                  <span class="name" v-else>
                    {{ item.SY_CREATEUSERNAME }}
                    <span style="margin:0 10px;color: #396ad1;">{{ $t('_log.reply') }}</span>
                    {{ item.REPORTDP_REPLY_USERNAME }}
                  </span>
                  <!-- 详情时间 -->
                  <span
                    class="time"
                    style="margin-left:20px;"
                  >{{ formatTime(item.SY_CREATETIME) }}</span>
                  <!-- 删除 -->
                  <i
                    v-if="enableRemoveComment(item)"
                    class="jeicon jeicon-error remove"
                    @click="removeComment(item,index)" />
                    <!-- 回复 -->
                    <i
                      v-if="showReply(item)"
                      @click="reply(item)"
                      style="margin-left: 20px; cursor: pointer;"
                      class="jeicon jeicon-message" />
                </div>
                <div
                  class="text"
                  v-html="formatContent(item.REPORTDP_DPNR)" 
                />
                <!-- 头像 -->
                <div
                  class="photo"
                  style="top:0;"
                  v-html="formatPhoto(item.SY_CREATEUSERID)" />
              </div>
            </div>
            <div
              v-else
              class="comments"
              style="padding-left: 10px;">
              {{ $t('_log.zanwudianpingxinxi') }}
            </div>
            <div
              v-show="isDPUser || isReply"
              class="content-edit comment-edit"
              style="margin-top: 20px;"
            >
              <el-input
                ref="commentText"
                type="textarea"
                resize="none"
                maxlength="1000"
                v-model="commentText"
                :placeholder="`${getEn(`请输入您的${isReply?'回复':'点评'}信息`)}...`"
                autosize
              />
              <div
                class="button button-blue"
                @click="addComment"
              >
                {{ getEn(`发布${isReply?'回复':'点评'}`) }}
              </div>
              <div class="text-num">
                {{ (commentText || '').length }}/1000
              </div>
            </div>
          </div>
        </div>
        <div class="buttonbar">
          <div
            v-if="isCurrentUser"
            style="width: 90px"
            class="button button-blue"
            @click="doEdit('edit')"
          >
            {{ readOnly?$t('_log.editor'):$t('_log.save') }}
          </div>
          <div
            class="button"
            style="width: 90px"
            :class="{'button-blue':!isCurrentUser}"
            @click="doEdit('cancel')"
          >
            {{ readOnly?$t('_log.close'):$t('_log.cancel') }}
          </div>
        </div>
      </el-card>
      <i
        class="el-dialog__close el-icon el-icon-close"
        @click="handleClose" />
    </el-dialog>
  </div>
</template>

<script>
import Cookies from 'js-cookie';
import uploadbox from '../../components/uploadbox';
import downloadItem from '../../components/downloadItem';
import Util from '../../util/util.js';
import spe from './../../assets/lang/log/speNationalList';

export default {
  name: 'Loginfo',
  components: { downloadItem, uploadbox },
  data() {
    return {
      visible: false,
      readOnly: true,
      loading: false,
      index: 0,
      data: {
        readList: [],
      },
      commentText: '',
      comments: [],
      isNoticeRefresh: false,
      filelist: [],
      isReply: false,
      replylen: 0,
      replyItem: {},
      lang: '',
    };
  },
  mounted() {
    if (Cookies.get('je-local-lang')) {
      this.$i18n.locale = Cookies.get('je-local-lang');
      this.lang = Cookies.get('je-local-lang');
    } else {
      Cookies.set('je-local-lang', this.$i18n.locale);
    }
  },
  computed: {
    /**
     * 是否当前用户
     */
    isCurrentUser() {
      return this.data.SY_CREATEUSERID == JE.USER.userId;
    },
    /**
     * 当前用户是否点评人
     */
    isDPUser(){
            return !this.isCurrentUser && JE.split(this.data.REPORT_DPR_ID,',').indexOf(JE.USER.userId) != -1;
        },
    /**
     * 计算高度
     */
    contentStyle(){
            var bodyHeight = JE.getBodyHeight(),
                height = bodyHeight-260;
            return {height:height+'px'};
        },
    /**
     * 格式化信息
     */
    info() {
      let me = this;
      let item = me.data;
      let start = item.REPORT_KSSJ;
      var end = item.REPORT_JSSJ;
      let time = '';
      var text = '';
      var type = '';
      switch (item.REPORT_BGLX_CODE) {
        case 'RZ':
          time = start;
          text = '日';
          type = 'RZ';
          break;
        case 'ZB':
          time = `${start} 到 ${end}`;
          text = '周';
          type = 'ZB';
          break;
        case 'YB':
          time = start.substring(0, 7);
          text = '月';
          type = 'YB';
          break;
      }
      return {
        text,
        time,
        type,
      };
    },
  },
  methods: {
    formatContent(content, defVal) {
      content = content || defVal || '';
      return content.replace(/\n/g, '<br>');
    },
    enableRemoveComment(item) {
      return item.SY_CREATEUSERID == JE.USER.userId;
    },
    /**
         * 格式化日期
         */
    formatTime(time){
      var d = moment(time).fromNow();
      if (d.indexOf("天") != -1) {
        return time.substr(0, 10);
      } 
      return d;
        
    },
    formatPhoto(id) {
      return JE.getUserPhoto(id, true);
    },
    setVisible(visible, id) {
      const that = this;
      this.visible = visible;
      this.readOnly = true;
      if (this.$refs.content) { this.$refs.content.scrollTop = 0; }
      this.comments = [];
      if (visible) {
        // 根据传过来的日志id查询详情
        const params = { JE_CIRCLE_REPORT_ID: id };
        const res = JE.ajax({
          url: '/je/workLog/loadTask',
          params,
        });
        if (res.success) {
          that.data = res.obj;
          that.filelist = [];
          if (res.obj.REPORT_FJ && res.obj.REPORT_FJ.length > 0) {
            that.filelist = JSON.parse(res.obj.REPORT_FJ);
          }
          // that.comments = res.obj.commentList;
          that.loadComments();
          Util.doReadMark('log', that.data.JE_CIRCLE_REPORT_ID);
          that.$emit('refreshItem', that.data, that.index);
        }
        // this.loadComments();
        // const result = await JE.ajax({ url: '/je/workLog/loadTask', params, async: false });
        // if (this.data.SY_FUNCEDIT != '0') {
        //   Util.doReadMark('log', this.data.JE_CIRCLE_REPORT_ID);
        //   this.data.SY_FUNCEDIT = '0';
        //   this.$emit('refreshItem', this.data, this.index);
        // }
      }
    },
    addComment(){
      var me = this;
      if(JE.isEmpty(me.commentText.trim())){
        JE.alert(`${this.getEn(`请输入${this.isReply?'回复':'点评'}内容`)}！`);
        return;
      }
      let params = {
          tableCode:'JE_CIRCLE_REPORTDP',
          REPORTDP_DPNR:me.commentText,
          JE_CIRCLE_REPORT_ID:me.data.JE_CIRCLE_REPORT_ID
        };
      if (this.isReply) {
        params.REPORTDP_DPNR = params.REPORTDP_DPNR.replace(`@${this.replyItem.SY_CREATEUSERNAME}  `, '');
        params.REPORTDP_REPLY_DPID = this.replyItem.JE_CIRCLE_REPORTDP_ID,
        params.REPORTDP_REPLY_USERNAME = this.replyItem.SY_CREATEUSERNAME,
        params.REPORTDP_REPLY_USERID = this.replyItem.SY_CREATEUSERID
      }
      JE.ajax({
        url:'/je/portal/homePortal/saveTaskComment',
        params,
        async:true,
        success:function(response){
          var data = JE.getAjaxData(response);
          if(data.success){
            me.comments.unshift(data.obj);
            // me.comments.push(data.obj);
            me.commentText = '';
            if (me.isReply) {
              me.isReply = false;
              me.replyItem = {};
            }
            JE.msg(`${me.getEn('评论成功')}！`);
            //更新点评人id
            var ids = JE.split(me.data.REPORT_YDPR_ID,',');
            if(ids.indexOf(JE.USER.userId) == -1){
              ids.push(JE.USER.userId);
            }
            me.data.REPORT_YDPR_ID = ids.join(',');
            me.$emit('changeReadState', me.index);
            me.$emit('refreshItem',me.data,me.index);
          } else {
            JE.alert(data.obj);
          }
        }
      });
    },
    removeComment(item, index) {
      let me = this;
      JE.confirm(`${me.$t('suredelete')}?`, (btn) => {
        if(btn == 'ok'){
          JE.ajax({
            url:JE.getUrlMaps('je.core.remove'),
            params:{
              tableCode:'JE_CIRCLE_REPORTDP',
              ids:item.JE_CIRCLE_REPORTDP_ID
            },
            async:true,
            success:function(response){
              var data = JE.getAjaxData(response);
              if(data.success){
                me.comments.splice(index,1);
                JE.msg(`${me.getEn('点评信息删除成功')}！`);
              }
            }
          });
        }
      });
    },
    loadComments() {
      let me = this;
      JE.ajax({
        url: JE.getUrlMaps('je.core.load'),
        params: {
          tableCode: 'JE_CIRCLE_REPORTDP',
          whereSql: `AND JE_CIRCLE_REPORT_ID='${me.data.JE_CIRCLE_REPORT_ID}'`,
          orderSql: 'order by SY_CREATETIME desc',
          j_query: Ext.encode({
            custom: [
              { type: '=', code: 'JE_CIRCLE_REPORT_ID', value: me.data.JE_CIRCLE_REPORT_ID },
            ],
            order: [
              { type: 'desc', code: 'SY_CREATETIME' },
            ],
          }),
          limit: -1,
        },
        async: true,
        success(response){
          var data = JE.getAjaxData(response);
          me.comments = data.rows;
        },
      });
    },
    noticeRefresh() {
      this.isNoticeRefresh = true;
    },
    handleClose(done) {
      this.visible = false;
      this.readOnly = true;
      this.setVisible(false);
      if (this.isNoticeRefresh) {
        this.$parent.childRefresh();
      }
    },
    /**
     * 编辑
     */
    doEdit(type) {
      let me = this;
      if (type == 'comment') {
        if (me.readOnly) {
          me.readOnly = false;
          me.$refs.content.scrollTop = me.$refs.content.scrollHeight;
        } else{
          me.updateInfo(type);
        }
      } else if (type == 'edit') {
        if (me.readOnly) {
          me.readOnly = false;
        } else{
          me.updateInfo();
        }
      } else if (type == 'cancel') {
        if (me.readOnly) {
          me.setVisible(false);
          if (this.isNoticeRefresh) {
            this.$parent.childRefresh();
          }
        }else {
          me.readOnly = true;
        }
      }
    },
    /**
     * 选择点评人
     */
    selectUser() {
      let me = this;
      JE.vue.selectUser({
        title: me.$t('selectreviewers'),
        width: 300,
        height: 500,
        multiple: true,
        value: me.data.REPORT_DPR_ID,
        valueType: 'id',
        callback(datas){
          var ids = [],texts = [];
          // 点评人去除本人
          const newDatas = datas.filter(item => item.id !== JE.getCurrentUser().id);
          Ext.each(newDatas,function(data){
            ids.push(data.id);
            texts.push(data.text);
          });
          if(ids.length>0){
            me.data.REPORT_DPR_ID = ids.join(',');//点评人
            me.data.REPORT_DPR_NAME = texts.join(',');//点评人姓名
          }
        },
      });
    },
    /**
     * 修改数据
     */
    updateInfo(type) {
      let me = this;
      var content = (me.data.REPORT_GZZJ || '').trim();
      if (type != 'comtent' && JE.isEmpty(content)) {
        JE.alert(`${this.getEn('请填写工作总结')}！`);
        me.$refs.summary.focus();
        return;
      }
      me.data.REPORT_FJ = JSON.stringify(this.filelist);
      let data = Ext.apply({
        tableCode: 'JE_CIRCLE_REPORT',
      }, me.data);
      me.loading = true;
      JE.ajax({
        // url: JE.getUrlMaps(`je.core.${JE.isEmpty(data.JE_CIRCLE_REPORT_ID)?'save':'update'}`),
        url: JE.isEmpty(data.JE_CIRCLE_REPORT_ID) ? JE.getUrlMaps('je.core.save') : '/je/workLog/doUpdate',
        params: data,
        async: true,
        success(response){
          var data = JE.getAjaxData(response);
          if(data.success){
            JE.msg(type == 'comment'?`${me.getEn('点评成功')}！`:`${me.getEn('保存成功')}！`);
            me.$emit('refreshItem',me.data,me.index);
            me.readOnly = true;
          }else{
            JE.alert(data.obj);
          }
          me.loading = false;
        },
      });
    },
    /**
     * 下载文件
     */
    download(file) {
      const type = file.name.substring(file.name.lastIndexOf('.') + 1);
      if('jpg,jpeg,png,gif'.indexOf(type) !== -1){
        // JE.File.openFileByPath(file.path,file.name,false,this.files);
        JE.File.doAct('preview', '', '', file.path, file.name)
      }else{
        // window.open(JE.getFileUrl(file.path));
        JE.File.doAct('download', '', '', file.path, file.name)
      }
      // e.stopPropagation();
      // const $a = document.createElement('a');
      // // const path = JE.getFileUrl(file.filePath,'','','','VIP_PFUP_MANAGER');
      // const path = JE.getFileUrl(file.filePath);
      // $a.setAttribute('href', path);
      // $a.setAttribute('download', file.fileName);
      // $a.click();
    },
    getList(list) {
      this.filelist = list;
    },
    // 回复
    reply(item) {
      this.$nextTick(() => {
        this.replyItem = item;
        this.isReply = true;
        const ele = document.querySelectorAll('.pro-gzq-home-log-info .el-dialog.is-fullscreen .info-box .content')[0];
        setTimeout(function() {
          ele.scrollTop = ele.scrollHeight;
        }, 0);
        this.commentText = `@${item.SY_CREATEUSERNAME}  `;
        this.replylen = this.commentText.length;
        this.$refs.commentText.blur();
      });
    },
    showReply(item) {
      return this.isCurrentUser && (item.SY_CREATEUSERID != JE.USER.userId);
    },
    getTimeEn(cn) {
      if (!cn) return;
      if (this.lang == 'zh_CN') return cn;
      if (this.data.REPORT_BGLX_CODE == 'RZ') {
        return this.data.REPORT_KSSJ
      }
      if (this.data.REPORT_BGLX_CODE == 'ZB') {
        return `${this.data.REPORT_KSSJ} to ${this.data.REPORT_JSSJ}`;
      }
      if (this.data.REPORT_BGLX_CODE == 'YB') {
        return this.data.REPORT_KSSJ.substring(0, 7);
      }
    },
    getEn(cn) {
      if (!cn) return;
      if (this.$i18n.locale == 'zh_CN') return cn;
      return spe[cn] || cn;
    },
  },
};
</script>
